package com.robot.search.controller;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author Hujf
 * @title: FileController
 * @date 2024-03-15 23:45
 * @description: TODO
 */
@RestController
public class FileController {

    @Value("${file.upload-dir}")
    private String UPLOAD_DIRECTORY;


    @Value("${file.index-dir}")
    private String INDEX_DIRECTORY;

    @PostMapping("/upload")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "Please select a file to upload.";
        }

        try {
            // Create directory if not exists
            File uploadDir = new File(UPLOAD_DIRECTORY);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            // Save the file to the server
            String fileName = file.getOriginalFilename();
            File dest = new File(UPLOAD_DIRECTORY + "/" + fileName);
            file.transferTo(dest);

            // Index the file content
            indexFile(dest);
            return "File uploaded successfully: " + fileName;
        } catch (IOException e) {
            return "Error uploading file: " + e.getMessage();
        }
    }

    private void indexFile(File file) throws IOException {
        // 创建索引

        // 1.创建一个Directory对象，使用FSDirectory.open打开磁盘上的索引库
        Directory directory = FSDirectory.open(new File(INDEX_DIRECTORY).toPath());
        // 2.创建一个indexWriter，指定使用Ik分词器
        IndexWriter indexWriter = new IndexWriter(directory,new IndexWriterConfig(new IKAnalyzer()));

        Document document = new Document();
        document.add(new TextField("title", file.getName(), Field.Store.YES));

        //获取pdf内容
        // 使用 Tika 解析 PDF 文件
        Tika tika = new Tika();
        try {
            String content = tika.parseToString(file);
            document.add(new TextField("content", content, Field.Store.YES));
        } catch (TikaException e) {
            throw new RuntimeException(e);
        }

        indexWriter.addDocument(document);
        indexWriter.close();

    }
}
